package han.study.preparedstatement.curd;

import han.study.bean.Order;
import han.study.utils.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class OrderForQuery {
    public Order orderForQuery(String sql, Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            rs = ps.executeQuery();
            // 获取查询元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            // 通过结果集获取列数
            int columnCount = rsmd.getColumnCount();

            if(rs.next()){
                Order order = new Order();
                for(int i=1;i<=columnCount;i++){
                    Object columnValue = rs.getObject(i);
                    // 由于数据库表格中类的列名和类Bean中类名不一致 所以使用列的别名来进行修改
                    // 获取列的列名
                    //String columnName = rsmd.getColumnName(i);
                    // 获取列的别名
                    String columnLabel = rsmd.getColumnLabel(i);
                    Field field = Order.class.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(order,columnValue);
                }
                return order;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.closeResource(conn,ps,rs);
        }
        return null;
    }

    @Test
    public void orderQuery(){
        String sql = "select order_id orderId, order_name orderName,order_date orderDate from `order` where order_id = ?";
        Order order = orderForQuery(sql,1);
        System.out.println(order);
    }
}
